package handler

import (
	"context"
	"encoding/json"
	"time"

	"github.com/micro/micro/v3/service/errors"
	log "github.com/micro/micro/v3/service/logger"

	posts "gitee.com/taadis/services/posts/proto"
	"github.com/gosimple/slug"
	gostore "github.com/micro/go-micro/v3/store"
	"github.com/micro/micro/v3/service/store"
)

type Post struct {
	Id              string   `json:"id"`
	Title           string   `json:"title"`
	Slug            string   `json:"slug"`
	Content         string   `json:"content"`
	CreateTimestamp int64    `json:"create_timestamp"`
	UpdateTimestamp int64    `json:"update_timestamp"`
	TagNames        []string `json:"tagNames"`
}

type Posts struct{}

// Delete
func (p *Posts) Delete(ctx context.Context, req *posts.DeleteRequest, resp *posts.DeleteResponse) error {
	return nil
}

// Save
func (p *Posts) Save(ctx context.Context, req *posts.SaveRequest, resp *posts.SaveResponse) error {
	log.Info("接收到 Posts.Save 请求")
	if len(req.Post.Id) == 0 || len(req.Post.Title) == 0 || len(req.Post.Content) == 0 {
		return errors.BadRequest("posts.Save", "Id, Title or Content is missing")
	}

	post := &Post{
		Id:              req.Post.Id,
		Title:           req.Post.Title,
		Content:         req.Post.Content,
		Slug:            slug.Make(req.Post.Title),
		TagNames:        req.Post.TagNames,
		CreateTimestamp: time.Now().Unix(),
		UpdateTimestamp: time.Now().Unix(),
	}

	buf, err := json.Marshal(post)
	if err != nil {
		return err
	}

	return store.Write(&gostore.Record{
		Key:   post.Slug,
		Value: buf,
	})
}
